package com.cskaoyan.user.controller;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.mall.commons.util.jwt.JwtTokenUtils;
import com.cskaoyan.user.dto.KaptchaCodeResponse;
import com.cskaoyan.user.dto.Token;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.form.KaptchaCodeRequest;
import com.cskaoyan.user.form.UserLoginRequest;
import com.cskaoyan.user.service.IKaptchaService;
import com.cskaoyan.user.service.ILoginService;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    ILoginService loginService;
    @Autowired
    IKaptchaService kaptchaService;

    /**
     * @Author Chen
     * @Date 2022-09-20  21-43-41
     * @param
     * @return {@link null }
     * @description  用户登录
     */
    @PostMapping("login")
    public ResponseData userLogin(@RequestBody UserLoginRequest userLogin,HttpServletRequest request, HttpServletResponse response){

        ResponseUtil responseUtil = new ResponseUtil();

        //获取验证码
        String kaptchaUuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        String captcha = userLogin.getCaptcha();

        KaptchaCodeRequest kaptchaCodeVerify = new KaptchaCodeRequest();
        kaptchaCodeVerify.setUuid(kaptchaUuid);
        kaptchaCodeVerify.setCode(captcha);

        KaptchaCodeResponse kaptchaCodeResponse = kaptchaService.validateKaptchaCode(kaptchaCodeVerify);
        String imageCode = kaptchaCodeResponse.getImageCode();

        //判断验证码是否正确
        if (!imageCode.equalsIgnoreCase(captcha)){
            ResponseData loginError = responseUtil.setErrorMsg("验证码错误");
            return loginError;
        }


        UserLoginResponse loginResponse = loginService.login(userLogin);

        if (loginResponse==null){
            ResponseData loginError = responseUtil.setErrorMsg("用户名或密码错误,确认账户是否激活");
            return loginError;
        }

        //TIP:生成token字符串，是浏览器下一次登录时携带我们加密后的token字符串
        Token tokenObj = new Token(loginResponse.getId(),loginResponse.getUsername());

        String tokenStr= JSON.toJSONString(tokenObj);
        String token = JwtTokenUtils.builder().msg(tokenStr).build().creatJwtToken();

        Cookie cookie = new Cookie("access_token",token);
        cookie.setPath("/");
        response.addCookie(cookie);

        loginResponse.setToken(token);
        ResponseData responseData = responseUtil.setData(loginResponse);

        return responseData;
    }

    /**
     * @Author Chen
     * @Date 2022-09-21  15-45-04
     * @param
     * @return {@link null }
     * @description   验证用户登录状态
     */
    @GetMapping("login")
    public ResponseData verifyLogin(HttpServletRequest request){

        String user_info = request.getHeader("user_info");

        System.out.println(user_info);

        ResponseUtil responseUtil = new ResponseUtil();

        if (!StringUtils.isEmpty(user_info)){

            ResponseData responseData = responseUtil.setData(user_info);
            return responseData;
        }

        ResponseData noLogin = responseUtil.setErrorMsg("您还未登录，请先登录");
        return noLogin;
    }

    /**
     * @Author Chen
     * @Date 2022-09-21  15-37-59
     * @param
     * @return {@link null }
     * @description   用户退出登录
     */
    @GetMapping("loginOut")
    public ResponseData logout(HttpServletRequest request,HttpServletResponse response){

        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("access_token")){
                //TIP: 用户退出登录时，将用户的token值设置为null
                cookie.setValue(null);
                cookie.setPath("/");
                cookie.setMaxAge(0);
                response.addCookie(cookie);
                break;
            }
        }


        ResponseUtil responseUtil = new ResponseUtil();
        ResponseData responseData = responseUtil.setData(null);

        return responseData;
    }
}
